package com.servlet.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Title: JDBCHelper  jdbc 的工具类
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/11/23 9:04
 */
public class JDBCHelper {

    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    public static Connection getConnection() throws SQLException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        Connection conn = threadLocal.get();
        if(conn == null) {
            conn = dataSource.getConnection();
            threadLocal.set(conn);
        }
        // 2 获取连接
          return conn;
    }

    public static void beginTransform() throws SQLException {
        //
        Connection conn = getConnection();
        conn.setAutoCommit(false);
    }

    public static void commitTransform() throws SQLException {
        Connection conn = getConnection();
        conn.commit();
    }

    public static void rollbackTransform() throws SQLException {
        Connection conn = getConnection();
        conn.rollback();
    }

    /**
     * 释放资源
     */
    public static void release()  {
        threadLocal.remove();
    }


}
